﻿/**
 * 公共函数
 * @type 
 */
var common = {
	/**
	 * 全局变量
	 * @type 
	 */
		/**
		 * 远程调用(一般调用)
		 * @param {} url
		 */
		invoke : function(args){
			$.ajax({
				url: args.url,
	            type: 'POST',
	            dataType: args.dataType?args.dataType:'text',
	            async: args.async == false?false:true,
	            contentType : args.contentType?args.contentType:'application/x-www-form-urlencoded',
	            data: args.params,
	            error: function () {
	                if(args.error){
	            		args.error();
	            	}
	            },
	            success: function (text) {
	               if(args.success){
		                args.success(json);
	            	}
	            }
			});
		},
		/**
		 * 删除弹出窗口(一般调用)
		 * @param {} url
		 */
		delpopup : function(args){
			console.info(args)
			
		},
		//    弹出提示框
    	loading: function(message) {
			mini.mask({
				el: document.body,
				cls: 'mini-mask-loading',
				html: message
			});
		},
		//    取消遮罩
    	unmask: function(){
			setTimeout(function () {
				mini.unmask(document.body);
			}, 500);
		},
        //提示信息
        prompt: function (msg) {
            // var messageId = mini.loading(msg, "消息提示");
            // setTimeout(function () {
            //     mini.hideMessageBox(messageId);
            // }, 2000);
            mini.showTips({
                content: msg,
                state: 'default',
                x: 'center',
                y: 'center',
                timeout: 3000
            });
        },
    	labelModel: function(form) {
			var fields = form.getFields();
			for (var i = 0; i < fields.length; i++) {
				var c = fields[i];
				if (c.setReadOnly) c.setReadOnly(true);     //只读
				if (c.setIsValid) c.setIsValid(true);      //去除错误提示
				// if (c.addCls) c.addCls("asLabel");          //增加asLabel外观
			}
		},
//		上传文档
		uploadFiles : function(params){
			var accept = params.config.accept?params.config.accept:'';
			var multiple = params.config.multiple;
			var container = params.config.container;
			var sync = (params.config.sync==false)?params.config.sync:true;
			var form = $('<form name="fileForm" id="fileForm" method="post" enctype="multipart/form-data"></form>').css({visibility:'hidden'});
			var file = $('<input type="file" name="file" class="file" id="file" />');
			
			if(multiple){
				file.attr('multiple', 'multiple');
			}
			form.append(file).appendTo('body');
			
			if(accept){
				file.attr('accept', accept);
			}
			file[0].addEventListener("change", function(){
				console.log(sync)
				console.log("--------------------")
				if(sync){
                    // var str = $(this).val();
			        // var fileName = common.getFileName(str);
			        // var fileExt = str.substring(str.lastIndexOf('.') + 1);
                    // $(".flex-filebox").empty();
			        // var fileBox = "<div class='flex-file'>"+
				    	// 		"<a class='flex-filename'>"+fileName+"</a>"+
				    	// 		/*"<span class='img-wh'></span>"+*/
			   		// 		"</div>";
			        // $(".flex-filebox").append(fileBox);
			        var forms = form[0];
			        var data = new FormData(forms);
			        var files = document.querySelector('[type=file]');
			        data.append('file', files.files[0]);
			        $.ajax({
			            type: "POST",
			            enctype: 'multipart/form-data',
			            url: "/ftp/ftpFileUpload",
			            data: data,
			            processData: false,
			            contentType: false,
			            cache: false,
			            timeout: 600000,
			            success: function (data) {
                            $(".flex-filebox").empty();
                            var fileBox = "<div class='flex-file'>"+
                                "<a class='flex-filename'>"+data.fileName+"</a>"+
                                "</div>";
                            $(".flex-filebox").append(fileBox);
			            	params.success(data);
			            },
			            error: function (e) {
			                console.log("ERROR : ", e);
			            }
			        });
				}
			}, false);
			file.click();
			return form[0];
	},
//	获取文件名称
	getFileName :function(path){
		var pos1 = path.lastIndexOf('/');
	    var pos2 = path.lastIndexOf('\\');
	    var pos = Math.max(pos1, pos2);
	    if (pos < 0) {
	        return path;
	    }
	    else {
	        return path.substring(pos + 1);
	    }
	},
    //下载模板
    downFile:function(url,name){
        window.location.href = "/ftp/downFile?path="+url+"&fileName="+name;
    },
    delFile:function(fid,url){
        $.ajax({
            type : "post",
            url : "/file/del?id="+fid+"&file_url="+url,
            success : function(msg) {
                console.log(msg)
                if(msg.state){
                    templeteFileName = "";
                    templeteUrl = "";
                    $(".flex-filebox").empty();
                }
            }
        });
    },
//	区域联动
	area:{
		init: function(obj){
			var region = $(obj);
			var content = '<input id="provinceCombo" class="mini-combobox w100" textField="province" valueField="id" url="/nation/getAllProvince" onvaluechanged="common.area.provinceChanged()" required="true" errorMode="none" >'+
                '<input id="cityCombo" name="cityId" class="mini-combobox w100" textField="city" valueField="id" onvaluechanged="common.area.cityChanged()" required="true" errorMode="none" onvalidation="onChoseValidation" requiredErrorText="请选择">';
			region.append(content);
		},
		//改变省
		provinceChanged: function(){
			var provinceCombo = mini.get("provinceCombo");
		    var cityCombo = mini.get("cityCombo");
		    var id = provinceCombo.getValue();
		    cityCombo.setValue("");
		    var url = "/nation/getListByPid?pid=" + id;
		    cityCombo.setUrl(url);
		},
		//改变市
		cityChanged: function(){
			var cityCombo = mini.get("cityCombo");
		    var regionCombo = mini.get("regionCombo");
		    var id = cityCombo.getValue();
		    /*regionCombo.setValue("");
		    var url = "/region/listByCity?cityId=" + id
		    regionCombo.setUrl(url);*/
		}
	},
    //区域联动
    areaItem:{

        init: function(parmes){
            var opt = {
                idName:'#areaItem',
				isItem: false
            };
            var opts = $.extend({},opt,parmes);
            var region = $(opts.idName);
            var content = '<input id="provinceCombo" class="mini-combobox w100" textField="province" valueField="id" ajaxType="post" url="/item/getProvinceWithItem" onvaluechanged="common.areaItem.provinceChanged('+opts.isItem+')" required="true" errorMode="none" >'+
                '<input id="cityCombo" name="cityId" class="mini-combobox w100" textField="city" valueField="id" ajaxType="post" onvaluechanged="common.areaItem.cityChanged('+opts.isItem+')" required="true" errorMode="none" onvalidation="onChoseValidation" requiredErrorText="请选择">';
            region.append(content);
        },
        //改变省
        provinceChanged: function(opts){
            var provinceCombo = mini.get("provinceCombo");
            var cityCombo = mini.get("cityCombo");
            var id = provinceCombo.getValue();
            cityCombo.setValue("");
            var url = "/item/getCityWithProvince?provinceId=" + id;
            cityCombo.setUrl(url);
			if(opts==true){
                var itemCombo = mini.get("itemCombo");
                var itemurl = "/item/getItemWithCityId?provinceId=" + id;
                itemCombo.setUrl(itemurl);
			}
        },
        //改变市
        cityChanged: function(opts){
            var cityCombo = mini.get("cityCombo");
            var regionCombo = mini.get("regionCombo");
            var id = cityCombo.getValue();
            if(opts==true){
                var itemCombo = mini.get("itemCombo");
                var itemurl = "/item/getItemWithCityId?cityId=" + id;
                itemCombo.setUrl(itemurl);
            }
        }
    },
//	年份选择
	makeYear:function() {
		var year = document.getElementById("year");
		var my = new Date();
		var endYear = my.getFullYear();// 获取当前年份
		var arr = [];
		for (var i = endYear; i > (endYear-20); i--) {
            var item = {"id":i,"text":i};
			arr.push(item);
		}
        mini.get(year).setData(arr);
	},
	changeYears:function(parmes){
        var opt = {
            idName:'#yearItem',
            isItem: false
        };
        var opts = $.extend({},opt,parmes);
        var region = $(opts.idName);
        var content = '<input id="year" name="year" class="mini-combobox w100" textField="text" valueField="id" textfield="text"/><span class="unit-span">年</span>'+
            '<input id="month" name="month" class="mini-combobox w100" textField="text" valueField="id"><span class="unit-span">月</span>';
        region.append(content);
        mini.parse();
        var my = new Date();
        var endYear = my.getFullYear();// 获取当前年份
        var endMonth = my.getMonth()+1;// 获取当前月份
        var arr = [];
        for (var i = (endYear+2); i > ((endYear+2)-12); i--) {
            var item = {"id":i,"text":i};
            arr.push(item);
        }
        //设置月份
        var result = [];
        for(var k = 0; k < 12; k++) {
        	var m = k+1;
            m = m < 10 ? "0" + m : m;
            //在这里可以自定义输出的日期格式
            var mitem = {"id":m,"text":k+1};
            result.push(mitem);
        }
        //判断是否选择全年
		if(opts.isItem){
			result.unshift({'id':"","text":"全部"});

		}
        //动态设置月份
        if(endMonth){
            endMonth = endMonth < 10 ? "0" + endMonth : endMonth;
        }
        mini.get("year").setData(arr);
        mini.get("month").setData(result);
        mini.get("year").setValue(endYear);
        mini.get("month").setValue(endMonth);
	},
    //业务类型
    busiType : function(){
        var busiType = mini.get("businessTypeId");
        var busiTypeName = busiType.value;
        $.ajax({
            url:"/businessType/list" ,
            data:{"pageSize":20 ,"pageIndex":0},
            type: "post"
        }).done(function(res) {
            if(res){
                var data=mini.decode(res);
                mini.get("businessTypeId").setData(data.data);
            }
        });
    },
    //获取公司树
    company:function(params){
        $.ajax({
            type: "post",
            url: "/org/companys",
            //data: "name=John&location=Boston",
            success: function(msg){
                var headCompany = msg.headCompany;
                var childCompanyList = msg.childCompanyList;
                var object = childCompanyList.push(headCompany);
                mini.get("affiliatedCompanyId").loadList(childCompanyList, "id", "parentid");
                mini.get("affiliatedCompanyId").loadList(childCompanyList, "id", "parentid");
            }
        });
    },
//	选择项目
    projectTree:function(){
        $.ajax({
            url:"/item/findTreeOrgItem" ,
            type: "post"
        }).done(function(res) {
            if(res){
                var data=mini.decode(res);
                var project = mini.get("projectId");
                project.loadList(data, "id", "pid");
            }
        });
	},
    //	选择项目
    choseProjectTree:function(){
        $.ajax({
            url:"/tree/itemInfo/findTreeToBuild" ,
            type: "post"
        }).done(function(res) {
            if(res){
                var data=mini.decode(res);
                var project = mini.get("projectTreeId");
                project.loadList(data, "id", "pid");
            }
        });
    },
    //	选择项目
    planProjectTree:function(params){
        $.ajax({
            url:"/statis/list/TreePlanVo",
            data:{'code':params},
            type: "post"
        }).done(function(res) {
            if(res){
                var data=mini.decode(res);
                var planId = mini.get("planId");
                planId.loadList(data, "id", "pid");
            }
        });
    },
//	组织架构
    loadTree:function(params){
        $.ajax({
			url:"/org/loadTree" ,
            type: "post"
        }).done(function(res) {
            if(res){
                var data=mini.decode(res);
                params.success(data);
            }
        });
	},
    //选择人员
    onButtonEdit :function(e,text) {
    var buttonEdit = e.sender;
    var win = mini.createTopSingle(TreeSelectWindow);
    win.set({
       multiSelect: (text?true:false),
//                showFolderCheckBox: true,
//                checkRecursive: true,
        url:"/org/loadTree",
        title: "选择人员",
        width: 520,
        height: 500
    });

    win.show();

    //初始化数据
    win.setData(null, function (action) {
        if (action == "ok") {
            //获取数据
            var node = win.getData();
            if (node) {

                buttonEdit.setValue(node.id);
                buttonEdit.setText(node.name);
            }
        }
    });
},
    //监听责任人为部门赋值
    nodeselect:function(e){
        var tree = mini.get("managerId");
        var value = tree.getCheckedNodes(true);
        var officeName = value[value.length-1].name;
        var officeId = value[value.length-1].id;
        mini.get("officeName").setValue(officeName);
        mini.get("officeId").setValue(officeId);
    },
    beforenodeselect: function(e) {
        //禁止选中父节点flag或者item
        if (typeof e.selected.flag != "undefined") {
            if (e.selected.flag != 3) e.cancel = true;
        } else {  if (e.selected.item == false) e.cancel = true;}
	},
    beforenodeselectPlan:function (e) {
        //禁止选中父节点type或者item
        if (e.selected.type != 'plan') e.cancel = true;
    }
};